#!/usr/bin/env python3

from typing import List
import numpy
from numpy import random
# from random import random, randint
from numpy.random import rand, randint
import sys
sys.path.append(sys.path[0]+'/../')
from utils.tools import save_csv
from Cloud_Merge.Cloud_Merge import Obstacle

radius = 100
length = 4.43
width = 1.59
# 每个方块最多几辆车
max_pro = 0.9
max_num = 3
file_path = sys.path[0] + "/generate.d"


class Point:
    def __init__(self, x=0, y=0) -> None:
        self.x = x
        self.y = y


class Rectangle:
    def __init__(self, min_p: Point, max_p: Point) -> None:
        self.min_p = min_p
        self.max_p = max_p


def random_center(center: Point) -> Point:
    x = rand()
    y = rand()
    center.x += x
    center.y += y
    return center


def random_shape() -> Point:
    rect = Point(length, width)
    rect.x += rand() - 0.5
    rect.y += rand() - 0.5
    return rect


def random_heading():
    heading = randint(0, 360)
    return heading


def random_car(center: Point) -> Obstacle:
    car_class = randint(1, 3)
    car_center = random_center(center)
    car_shape = random_shape()
    car_heading = random_heading()
    car_score = rand()
    car = Obstacle(length=car_shape.x, width=car_shape.y, heading=car_heading, speed=0,
                   score=car_score, classification=car_class, longtitude=0, latitude=0)
    car.center_x = car_center.x
    car.center_y = car_center.y
    return car


def generate_test(rect: Rectangle) -> List[Obstacle]:
    # n*m rect，方块横摆
    from math import ceil
    n = ceil((rect.max_p.x - rect.min_p.x)/length)
    m = ceil((rect.max_p.y - rect.min_p.y)/width)
    cars = []
    # each rect has N car
    center = Point()
    center.x = rect.min_p.x
    for i in range(n):
        center.x = i * length + rect.min_p.x
        center.y = rect.max_p.y
        for j in range(m):
            center.y = center.y - width
            # each car center, shape, heading
            N = randint(0, max_num)
            gen = random.random()
            if gen > max_pro:
                for k in range(N):
                    car = random_car(center)
                    cars.append(car)
    return cars


def read_cars() -> List[Rectangle]:
    import yaml
    import os
    res = []
    folder = os.listdir(file_path)
    for f in folder:
        file = file_path + "/" + f
        file = open(file)
        yml = yaml.safe_load(file)

        test = yml["test"]
        rect = Rectangle(min_p=Point(float(test["min_x"]), float(test["min_y"])),
                         max_p=Point(float(test["max_x"]), float(test["max_y"])))
        res.append(rect)
    return res


if __name__ == '__main__':
    cars = read_cars()
    from utils.tools import pretty_print
    obs = None
    for car in cars:
        pretty_print(car)
        obs = generate_test(car)
    # for o in obs:
    #     pretty_print(o)
    save_csv(obs)
